import {Component, ElementRef, ViewChild} from '@angular/core';
import {Events, IonicPage, Navbar, NavController, NavParams} from 'ionic-angular';
import {StorageProvider} from "@providers/storage";
import {HttpProvider} from "@providers/http";
import {DialogProvider} from "@providers/dialog";
import {MapProvider} from "@providers/map"
import {Util} from "@providers/util";
import {Observable} from "rxjs";
/**
 * 师傅位置
 */

@IonicPage()
@Component({
  selector: 'page-manager-position',
  templateUrl: 'manager-position.html',
})
export class ManagerPositionPage {
  @ViewChild('map_container') map_container: ElementRef;
  @ViewChild(Navbar) navbar: Navbar;
  userInfo:any;
  contact = this.navParams.get("KEY");
  map: any;//地图对象
  timer:any;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private storageProvider:StorageProvider,
              private http:HttpProvider,
              private dialog:DialogProvider,
              private mapProvider:MapProvider,
              private events: Events) {
    this.userInfo = this.storageProvider.read('userInfo');
  }

  ionViewDidLoad() {
    Util.replaceBackButtonEvent(this.navbar, this.navCtrl, this.events);
    this.initMap();
  }

  ionViewWillUnload(){
    //页面离开时取消定时器
    if(this.timer){
      this.timer.unsubscribe();
    }
  }

  //初始化地图
  initMap(){
    this.mapProvider.createMap(this.map_container.nativeElement).then((map)=>{
      this.map = map;
      this.getPosition()
    });
  }

  //联网查看坐标
  getPosition(){
    this.timer = Observable.timer(0,60000).subscribe(()=>{
      this.http.post("/Inbound/invoke.do", {
        interfaceId: "csm.som.jcdy.qcfwtools.geopointlist.query",
        data: JSON.stringify({'RYXX01': this.userInfo.RYXX01,'RYBM':this.contact})
      }).subscribe(message => {
        let positions = message.data;
        positions.forEach(value=>{
          let market = this.mapProvider.addMarker({'lng':value.LONGITUDE,'lat':value.LATITUDE});
          let content =  `<ul class='main'>
                <li class='w12'>司机名称：<span style='color:blue'>${value.NAME}</span></li>
                <li class='w12'>联系电话: <span style='color:blue'>${value.LXDH}</span></li>
                </ul>`;
          this.mapProvider.addInfoWindow(market,content);
        });
        this.map.setFitView();
      }, error => {
        this.dialog.showAlert('请检查网络！' + error,'',()=>{
          this.events.publish("isBackButtonOfIonic");
          this.navCtrl.pop();
        });
        this.dialog.hideLoading();
      });
    });
  }
}
